package cn.golxen.blog.service.impl;

import cn.golxen.blog.commons.vo.AddLabelSetVo;
import cn.golxen.blog.commons.vo.GetLabelAndEssayCountVo;
import cn.golxen.blog.entity.Essay;
import cn.golxen.blog.entity.Label;
import cn.golxen.blog.exception.exceptionClass.AddLabelException;
import cn.golxen.blog.exception.exceptionClass.DeleteLabelException;
import cn.golxen.blog.mapper.EssayLabelMapper;
import cn.golxen.blog.mapper.LabelMapper;
import cn.golxen.blog.redis.EssayRedis;
import cn.golxen.blog.redis.LabelRedis;
import cn.golxen.blog.service.EssayService;
import cn.golxen.blog.service.LabelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Service
public class LabelServiceImpl implements LabelService {
    @Autowired
    @Qualifier(value = "taskExecutor")
    ThreadPoolTaskExecutor poolTaskExecutor;
    @Autowired
    LabelMapper labelMapper;
    @Autowired
    LabelRedis rLabel;
    @Autowired
    EssayLabelMapper essayLabelMapper;

    @Override
    public Integer addLabel(Label label) {
        Integer integer=labelMapper.addLabel(label);
        poolTaskExecutor.execute(()->{
//            rEssay.deleteLabelAll();
            rLabel.deleteLabelSet(label.getCategory());
        });
        return integer;
    }

    @Override
    public Integer deleteLabel(Label label) {
        Integer integer;

        if (getEssayCountByLabel(label.getLabel())==0)
            integer=labelMapper.deleteLabel(label.getLabel());
        else
            throw new DeleteLabelException();
        poolTaskExecutor.execute(()->{
//            lEssay.deleteLabelAll();
            rLabel.deleteLabelSet(label.getCategory());
        });
        return integer;
    }

    @Override
    public Set<GetLabelAndEssayCountVo> getLabelByCategory(String category) {
        return rLabel.getLabelByCategory(category);
    }

    @Override
    public Set<GetLabelAndEssayCountVo> getLabelAll() {
        return rLabel.getLabelAll();
    }

    @Override
    public Integer getEssayCountByLabel(String label) {
        return Integer.valueOf(rLabel.getEssayCountByLabel(label));
    }

    @Override
    public Integer getCount() {
        return rLabel.getCount();
    }

    @Override
    public Integer addLabelSet(AddLabelSetVo addLabelSetVo) {
        try {
            Integer integer=labelMapper.addLabelSet(addLabelSetVo);

        poolTaskExecutor.execute(()->{
//            rEssay.deleteLabelAll();
            rLabel.deleteLabelSet(addLabelSetVo.getCategory());
        });
        return integer;
        }catch (Exception e){
            e.printStackTrace();
            throw new AddLabelException();
        }
    }
}
